package com.learn.core.controller.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.Log;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.BusinessType;
import com.learn.common.enums.OperatorType;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.*;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.LOrganization;
import com.learn.core.domain.LQuestionsSort;
import com.learn.core.dto.LQuestionsSortDTO;
import com.learn.core.service.ILOrganizationService;
import com.learn.core.service.ILQuestionsSortService;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Description
 *
 * @author zhaohongyu
 * @ClassName LQuestionsSortController
 * @date 2021.03.22 09:42
 * @describe 试题分类
 */
@Api("试题分类")
@RestController
@RequestMapping("/manager/qsort")
public class LQuestionsSortController extends WebController<LQuestionsSort> {

    @Autowired
    private ILQuestionsSortService ilQuestionsSortService;
    @Autowired
    private ILOrganizationService ilOrganizationService;

    //试题分类树
    @ApiOperation(value = "试题分类树")
    @UserLoginToken
    @PostMapping("/tree")
    public CommonResult<Object> tree(){
        try {
            QueryWrapper<LQuestionsSort> queryWrapper = new QueryWrapper<LQuestionsSort>();
            queryWrapper.eq("state","1");
            List<LQuestionsSort> lOrganizations = ilQuestionsSortService.queryLQuestionsSortAll(queryWrapper);
            if(lOrganizations.size()>0)
                return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lOrganizations);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //列表
    @ApiOperation(value = "获取列表")
    @UserLoginToken
    @PostMapping("/list")
    public PageResult<LQuestionsSort> list(@RequestBody LQuestionsSortDTO lQuestionsSortDTO){
        try {
            if (lQuestionsSortDTO==null||lQuestionsSortDTO.getPage()==null||lQuestionsSortDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lQuestionsSortDTO.getPage(),lQuestionsSortDTO.getRows());
            QueryWrapper<LQuestionsSort> queryWrapper = new QueryWrapper<LQuestionsSort>();
            if(lQuestionsSortDTO.getParentNode()!=null)
                queryWrapper.eq("parent_node",lQuestionsSortDTO.getParentNode());
            else {
                queryWrapper.eq("parent_node","0");
            }
            if(lQuestionsSortDTO.getQuestionsSortName()!=null)
                queryWrapper.like("questions_sort_name",lQuestionsSortDTO.getQuestionsSortName());
            if(lQuestionsSortDTO.getState()!=null)
                queryWrapper.eq("state",lQuestionsSortDTO.getState());
            Page<LQuestionsSort> lQuestionsSorts = (Page<LQuestionsSort>) ilQuestionsSortService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lQuestionsSorts)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            for (LQuestionsSort lQuestionsSort : lQuestionsSorts) {
                LOrganization lOrganization = ilOrganizationService.getById(lQuestionsSort.getOrganizationId());
                if(null != lOrganization)
                    lQuestionsSort.setOrganizationName(lOrganization.getOrganizationName());
            }
            // 返回
            return new PageResult(lQuestionsSorts.getTotal(), lQuestionsSorts, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }


    //新增
    @ApiOperation(value = "添加")
    @PostMapping("/add")
    @UserLoginToken
    @Log(title = "添加试题分类", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> add(@RequestBody LQuestionsSort lQuestionsSort, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(lQuestionsSort!=null) {
                if (StringUtils.isEmpty(lQuestionsSort.getQuestionsSortName())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_QUESTIONS_SORT_NAME);
                }
                if (StringUtils.isEmpty(lQuestionsSort.getState())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_QUESTIONS_SORT_STATE);
                }
                if (StringUtils.isEmpty(lQuestionsSort.getParentNode())) {
                    lQuestionsSort.setParentNode(0);
                }

                lQuestionsSort.setCreateTime(new Date());
                lQuestionsSort.setCreateUser(userId);
                if (ilQuestionsSortService.save(lQuestionsSort)) {
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
                }
            }
        }catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return  (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }


    //删除
    @ApiOperation(value = "删除")
    @PostMapping("/del")
    @UserLoginToken
    @Log(title = "删除试题分类", businessType = BusinessType.DELETE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> del(@RequestBody LQuestionsSort lQuestionsSort){
        try {
            if(lQuestionsSort!=null){
                if(lQuestionsSort.getQuestionsSortId()!=null){
                    List<Integer> ids = new ArrayList<>();
                    ids.add(lQuestionsSort.getQuestionsSortId());
                    if(nodeStr(ids)){
                        return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
                    }
                }
            }
        }catch (Exception e)
        {
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    private Boolean nodeStr (List<Integer> lists) throws Exception{
        List<Integer> ids = new ArrayList<>();
        QueryWrapper<LQuestionsSort> queryWrapper = new QueryWrapper<LQuestionsSort>();
        for (int i = 0; i <lists.size() ; i++) {
            int orgid = lists.get(i);

            queryWrapper.eq("parent_node",orgid);
            List<LQuestionsSort> lQuestionsSorts = ilQuestionsSortService.list(queryWrapper);
            for (int j = 0; j < lQuestionsSorts.size(); j++) {
                LQuestionsSort lQuestionsSort = lQuestionsSorts.get(j);
                ids.add(lQuestionsSort.getQuestionsSortId());
            }
        }
        if(ids.size() > 0){
            this.nodeStr(ids);
        }

        ids.addAll(lists);
        queryWrapper = new QueryWrapper<LQuestionsSort>();
        queryWrapper.in(true, "questions_sort_id", ids);
        ilQuestionsSortService.remove(queryWrapper);

        return Boolean.TRUE;
    }

    //更新
    @ApiOperation(value = "更新")
    @PostMapping("/edit")
    @UserLoginToken
    @Log(title = "更新试题分类", businessType = BusinessType.UPDATE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> edit(@RequestBody LQuestionsSort lQuestionsSort, HttpServletRequest request) {
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        if(lQuestionsSort!=null){
            lQuestionsSort.setUpdateTime(new Date());
            lQuestionsSort.setUpdateUser(userId);
            if(ilQuestionsSortService.updateById(lQuestionsSort)){
                return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
            }
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }
}
